package com.zoe.onelink.business.util;

import com.zoe.onelink.business.constant.RequestConst;
import com.zoe.onelink.business.property.OnelinkExternalSystemProperties;
import com.zoe.onelink.common.enumeration.ExceptionCodeEnum;
import com.zoe.onelink.common.exception.ApiException;
import com.zoe.onelink.util.OnelinkContextHolder;
import com.zoe.onelink.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;

/**
 * <p>标题: 外部系统地址工具类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-08-09
 */
public class ExternalSystemUtil {

    @Autowired
    private OnelinkExternalSystemProperties externalSystemProperties;

    private static ExternalSystemUtil self;

    @PostConstruct
    public void init() {
        self = this;
    }

    /**
     * 获取外部系统地址
     * 优先级:
     * 1. 院区编码存在优先使用院区编码进行查询
     * 2. 默认地址
     *
     * @param systemName 系统名称
     * @return 不存在返回null
     */
    public static String getSystemUrl(String systemName) {
        if (StrUtil.isBlank(systemName)) {
            throw ApiException.createEx(ExceptionCodeEnum.VALUE_NOT_NULL, "ExternalSystemName");
        }
        String districtCode = OnelinkContextHolder.getString(RequestConst.HEADER_DISTRICT_CODE);
        String externalSystemUrl;
        if (StrUtil.isBlank(districtCode)) {
            externalSystemUrl = self.externalSystemProperties.getExternal().get(systemName);
        } else {
            String districtKey = systemName + "_district_" + districtCode;
            externalSystemUrl = self.externalSystemProperties.getExternal().get(districtKey);
            if (StrUtil.isBlank(externalSystemUrl)) {
                externalSystemUrl = self.externalSystemProperties.getExternal().get(systemName);
            }
        }
        return externalSystemUrl;
    }

}
